local RoomListLayer = class("RoomListLayer", function(scene)
	local roomlist_layer = display.newLayer()
    return roomlist_layer
end)
local ScrollDigital  = appdf.req("client.src.public.ScrollDigital")
local QueryExit = appdf.req(appdf.CLIENT_SRC.."app.views.layer.other.QueryDialog")
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
local ShareLayer = appdf.req(appdf.CLIENT_SRC .. "plaza.views.layer.plaza.ShareLayer")
local Room = appdf.req(appdf.CLIENT_SRC.."plaza.views.layer.room.RoomLayer")
local Update = appdf.req("client.src.controllers.ClientZipUpdate")
local QueryDialog = appdf.req("app.views.layer.other.QueryDialog")
local MultiPlatform = appdf.req(appdf.EXTERNAL_SRC .. "MultiPlatform")
local tbGameBt = {}
local boneEffectIdx = 1
local animationlist = {}
function RoomListLayer:ctor(scene, isQuickStart)
	ExternalFun.registerNodeEvent(self)
	self._scene = scene
	local this = self
	self.m_bIsQuickStart = isQuickStart or false
	self.downidx = 1
	self.enterRoomidInfo = {}
	local str = cc.FileUtils:getInstance():getStringFromFile(device.writablePath .."enterRoomidInfo.txt")
	if str ~= "" then
		self.enterRoomidInfo= cjson.decode(str)

	end

	
	
	self:initView()
end

function RoomListLayer:onExit()
	if self.customlistener ~= nil then
		appdf.removeListener(self.customlistener)
		self.customlistener = nil
	end
end
-- 进入场景而且过渡动画结束时候触发。
function RoomListLayer:onEnterTransitionFinish()
    return self
end

-- 退出场景而且开始过渡动画时候触发。
function RoomListLayer:onExitTransitionStart()
	self:unregisterScriptTouchHandler()
    return self
end

function RoomListLayer:initCfg( )
	self.downlist = self._scene:getApp()._serverConfig.downUrlLsit or {}
	GlobalUserItem.tb_gameType = self._scene:getApp()._serverConfig.name_type or {}
	self.game_ver_list = self._scene:getApp()._serverConfig.game_ver_list or {}
	
end

function RoomListLayer:iconSpecilCreate(gameid,aniTable)
	if gameid == yl.fruitslot then
		local lastjactpot = self:GetPreciseDecimal(self._scene:getJackPotNum()/1000,2) 
		aniTable[gameid].node = ScrollDigital.new( lastjactpot or 000000000,27.5):setTag(100)
	end
end

function RoomListLayer:iconSpecilAdd(gameid,aniTable,parent)
	if gameid == yl.fruitslot then
		if parent:getChildByTag(100) == nil then
			local size = parent:getContentSize()
			aniTable[gameid].node:addTo(parent):setPosition(cc.p(size.width/2-10,size.height/2-30)):setScale(0.8)
			aniTable[gameid].node:setVisible(false)
		end
	end
end

function RoomListLayer:iconSpecilUpdate(gameid,aniTable,data)
	if gameid == yl.fruitslot then
		--aniTable[gameid].node = ScrollDigital.new(000000000):addTo(animat)
	end
end
--根据config配置 检查场次进入多少次后关闭
function RoomListLayer:checkSeverCloseTiyan(roomid)
	local experienceLimit =  self._scene:getserverConfig().experienceLimit --experienceLimit
	experienceLimit = experienceLimit or {}
	local limitcount = experienceLimit[tostring(roomid) ] or 0
	return tonumber(limitcount) 
end

function RoomListLayer:initView(notAni)
	--动画数组 考虑到用到spine 和 cocos2d 自带的动画制作两种不同动画格式
	self.mAniTable = {}
	self:initCfg()
	--self:checkCloseTiyan()
	self.mAniTable ={
		[1000] = {file = "Armature/plazz/datingdonghua_fenxiangyingdajiang/datingdonghua_fenxiangyingdajiang.ExportJson",format="cocos",ani=nil,node=nil}
	}
if not self then	
	for k,v in pairs(GlobalUserItem.roomwithGameidlist) do
		local format = "cocos"
		local gametype = GlobalUserItem.tb_gameType[tostring(k)] or 1  --1 是默认版本 
		local str = string.format("Armature/plazz/game%d_%d/game%d_%d.ExportJson",k,gametype,k,gametype)
		if k == yl.fruitslot then
			str = string.format("Armature/plazz/game%d/shuiguojitubiao",k)
			format = "spine"
			self.mAniTable[k] = {file=str,format=format,ani=nil,node=nil}
			self:iconSpecilCreate(yl.fruitslot,self.mAniTable)
		else
			if gametype <= 1 or not cc.FileUtils:getInstance():isFileExist(str) then
				str = string.format("Armature/plazz/game%d/game%d.ExportJson",k,k)
			end
		end
		if cc.FileUtils:getInstance():isFileExist(str) then
			self.mAniTable[k] = {file=str,format=format,ani=nil,node=nil}
		end
	end
	
	ExternalFun.addArmatureCacheNew(self.mAniTable)
end
	self:removeAllChildren()
	local tempGamelist = {}
	animationlist = {}
	self.wServerTypeTable = {}
	tbGameBt = {}
if not self then	
	table.sort(GlobalUserItem.roomkindlist,function (a,b)
		if a.status == 1 and b.status == 1  then
			return a.orderid < b.orderid
		elseif a.status == 2 or b.status == 2 then
			return a.status < b.status
		end
		
	end)
end
	local roomlist = GlobalUserItem.roomkindlist
	local function btnEvent( sender, eventType )
		if eventType == ccui.TouchEventType.ended then
			sender:setScale(1)
			local tag = sender:getTag()
			--获取游戏信息
			local gameinfo = roomlist[tag]
			for k,v in pairs(gameinfo.roomls) do
				local limitCount =  self:checkSeverCloseTiyan(v.roomid) --进入多少次后关闭房间
				if limitCount ~= 0 then
					local hasEntercount =  self.enterRoomidInfo[tostring( v.roomid)] or 0
					if limitCount < hasEntercount then
						v.status = 0
					end
				end
				
			end
			
            local titlestatus = {"房间正在维护","正常","敬请期待"}
			if not gameinfo or gameinfo.status ~= 1 then
				showToast(self._scene ,titlestatus[gameinfo.status+1],4)
			return
			end
			self:btnTouched(gameinfo,sender)
		elseif eventType == ccui.TouchEventType.began then
			sender:setScale(yl.btscale)
			return true
		elseif eventType == ccui.TouchEventType.canceled then
			sender:setScale(1)
		end
	end


	self.typeLayer,typeCsbNode =  ExternalFun.loadRootCSB("plaza/typeLayer.csb", self)
	self.two_Panel = typeCsbNode:getChildByName("two_Panel")
	ExternalFun.FixCenterUI(self.two_Panel)
	self.gameListView = self.two_Panel:getChildByName("gameList")

	ExternalFun.FixScaleUI(self.gameListView,true,true,device.platform =="ios" and 0.8 or 1,true)

	self.gameDemoe = typeCsbNode:getChildByName("gameDemo")
	self.pagelayer = self.gameListView:getChildByName("pagelayer")
	self.share_page = self.pagelayer:getChildByName("share_page")
	local share_copy_layer = self.share_page:getChildByName("share_copy_layer")
	local share_angent_layer = self.share_page:getChildByName("share_angent_layer")
	
	local share_btn = share_angent_layer:getChildByName("share_btn")
	local share_copy_btn = share_copy_layer:getChildByName("share_btn")
	self.share_copy_layer = share_copy_layer
	self.share_angent_layer = share_angent_layer
	share_btn:setSwallowTouches(false)
	share_copy_btn:setSwallowTouches(false)
	share_copy_layer:setSwallowTouches(false)
	share_angent_layer:setSwallowTouches(false)
	self.share_page:setSwallowTouches(false)
	self:addShareAgent(share_btn)
	local function sharebtncallback(sender,eventType)
		if eventType == ccui.TouchEventType.ended then
			ExternalFun.playClickEffect( )
			local bvisible = self._scene:getTuiguanVisible( )
			if bvisible then
				self._scene:openAgents()
				return
			end
			
		--	sender:setScale(1)
			local sharelayer = ShareLayer:create(self._scene)
			self._scene:addChild(sharelayer,0)
			showToast(self._scene,"官网链接已复制，欢迎分享给您的小伙伴",2)
			if not GlobalUserItem.URLconfig  then
				showToast(self,"平台地址获取失败")
				return
			end
			local ret, msg = MultiPlatform:copyToClipboard(GlobalUserItem.URLconfig.url.."?channelid="..appdf.channelId)
			if ret == true then
				-- showToast(self._scene, "复制成功!", 1)
			else
				if type(msg) == "string" then
					showToast(self._scene, msg, 1, cc.c3b(250, 0, 0))
				end
			end
		elseif eventType == ccui.TouchEventType.began then
			--sender:setScale(yl.btscale)
			return true
		elseif eventType == ccui.TouchEventType.canceled then
			--sender:setScale(1)
		
		end
		
	end
	local function sharebtncallback2(sender,eventType)
		if eventType == ccui.TouchEventType.ended then
	
			ExternalFun.playClickEffect( )
		--	sender:setScale(1)
			local sharelayer = ShareLayer:create(self._scene)
			self._scene:addChild(sharelayer,0)
			showToast(self._scene,"官网链接已复制，欢迎分享给您的小伙伴",2)
			if not GlobalUserItem.URLconfig  then
				showToast(self,"平台地址获取失败")
				return
			end
			local ret, msg = MultiPlatform:copyToClipboard(GlobalUserItem.URLconfig.url.."?channelid="..appdf.channelId)
			if ret == true then
				-- showToast(self._scene, "复制成功!", 1)
			else
				if type(msg) == "string" then
					showToast(self._scene, msg, 1, cc.c3b(250, 0, 0))
				end
			end
		elseif eventType == ccui.TouchEventType.began then
		--	sender:setScale(yl.btscale)
			return true
		elseif eventType == ccui.TouchEventType.canceled then
		--	sender:setScale(1)
		
		end
		
	end
	share_copy_btn:addTouchEventListener(sharebtncallback2)
	local sharesize = share_copy_btn:getContentSize()
	local copybtn = ccui.Button:create("plaza/plazz/copybtn.png","plaza/plazz/copybtn.png")
	copybtn:addTouchEventListener(sharebtncallback2)
	copybtn:setPosition(sharesize.width/2,60)
	share_copy_btn:addChild(copybtn,33)
	--ExternalFun.addArmatureWithCustomNode("datingdonghua_fenxiangyingdajiang",share_copy_btn,nil,cc.p(sharesize.width/2,sharesize.height/2-37))
	table.insert(animationlist,self.share_page) 
	
	local app = self._scene:getApp()
	-- self.roomBtn = {}
	local m_fThird = 1
if not self then
	local lie = math.ceil(#GlobalUserItem.roomkindlist/2)
	for i = 1,lie do

		local itemlistView = self.gameDemoe:clone()
		itemlistView:setCascadeOpacityEnabled(true)
		table.insert(animationlist,itemlistView) 

		itemlistView:setVisible(true)
		for j = 1,2 do
			local bt = itemlistView:getChildByName(j)
			bt:setCascadeOpacityEnabled(true)
			local gameinfo = GlobalUserItem.roomkindlist[(i-1)*2+j]
       
			if  gameinfo  then
				local arma,animat 
				-- self.roomBtn[gameinfo.gameid] = bt
				if gameinfo then --and gameinfo.status == 1 then
					local arma,animat 
					if  self.mAniTable[gameinfo.gameid] ~= nil and self.mAniTable[gameinfo.gameid].format == "cocos" then
						local gametype = GlobalUserItem.tb_gameType[tostring(gameinfo.gameid) ] or 1
						local str = string.format("Armature/plazz/game%d_%d/game%d_%d.ExportJson",gameinfo.gameid,gametype,gameinfo.gameid,gametype)
						local str2 = string.format("game%d_%d",gameinfo.gameid,gametype)
						if gametype > 1 and cc.FileUtils:getInstance():isFileExist(str)  then	
							arma,animat = ExternalFun.addArmatureWithCustomNode(str2,bt)
						else
							arma,animat = ExternalFun.addArmatureWithCustomNode("game"..gameinfo.gameid,bt)
						end
					elseif self.mAniTable[gameinfo.gameid] ~= nil and self.mAniTable[gameinfo.gameid].format == "spine" then
						animat = self.mAniTable[gameinfo.gameid].ani
						animat:setPosition(bt:getContentSize().width /2,0)   
						:addTo(bt)
						:setTimeScale(1)
						animat:setAnimation(0, "", true)
						self:iconSpecilAdd(gameinfo.gameid,self.mAniTable,bt)
						--setPosition(cc.p(jackportpos.x-16,jackportpos.y)):
					else
						--if cc.FileUtils:getInstance():isFileExist("Armature/plazz/game"..gameinfo.gameid..".png") then
						local btsize = bt:getContentSize()
						-- arma,animat = ExternalFun.addArmatureWithCustomNode("game100",bt)
						display.newSprite("GameList/default.png"):move(btsize.width/2,btsize.height/2-4):addTo(bt)
						--	end
					end
					bt:setVisible(true)
					bt:setTag((i-1)*2+j)
					tbGameBt[gameinfo.gameid] = bt
					bt:addTouchEventListener(btnEvent)

					local downFlag = cc.Sprite:create("GameList/downFlag.png")
					local downflagsize = downFlag:getContentSize()
					local to1 = cc.ProgressTo:create(12, 100)
					local downbg = cc.Sprite:create("GameList/timerbg.png")
					display.newSprite("GameList/tuoyuan.png"):move(downflagsize.width/2,downflagsize.height/2+7):addTo(downFlag)
					downbg:setPosition(downflagsize.width/2,downflagsize.height/2+7)
					downbg:setName("downbg")
					downFlag:addChild(downbg)
					downFlag.arma = arma
					downFlag.animat = animat
					--用一个精灵 创建进度条
					for k,v in ipairs(gameinfo.roomls) do
						--体验场
						
						local tempty = string.find(v.name, "体验")
						if tempty  then
							local comperesult = self:comperEnterWithRoomid(v.roomid) 
							if comperesult then
								local sp = display.newSprite("public/experience.png")
								sp:setPosition(48,165)
								bt:addChild(sp)
							end
							
						end
					end
					local maskSp = cc.ProgressTimer:create(cc.Sprite:create("GameList/timesp.png"))
					--进度条类型：旋转型
					maskSp:setType(cc.PROGRESS_TIMER_TYPE_RADIAL)
					maskSp:setPosition(cc.p(54,54))
					--运行Action,这里用了一个cc.RepeatForever,其实下面那句效果相同。这是ProgressTimer与Sprite的区别
					--maskSp:runAction(cc.RepeatForever:create(to1))		
					if nil ~= maskSp and  not appdf.APPSTORE_VERSION  then			
							local size = bt:getContentSize()
							maskSp:setName("download_mask_sp")			
							downFlag:setAnchorPoint(cc.p(0,0))
							downFlag:setPosition(5,1.5)
							downbg:addChild(maskSp)
							if not bt:getChildByName("download_mask") then
								bt:addChild(downFlag)
							end
							downFlag:setName("download_mask")

						spTip = cc.Label:createWithSystemFont("0", "", 32)
							:move(54,54)
							:setName("download_mask_tip")
							:addTo(downbg)
						spTip:setVisible(false)
						display.newSprite("GameList/jiantou.png"):move(54,54):setName("download_mask_jt"):addTo(downbg)

						if nil ~= downFlag then

							local verinfo = string.split(self.game_ver_list[tostring(gameinfo.gameid)] or "","_") or {}
							local _severcfg_zipver = trim(verinfo[1] or "0")   --最新版本
							if _severcfg_zipver == "" or _severcfg_zipver == "0" then
								gameinfo.status = 2
							end

							local version = app:getVersionMgr():getResVersion(gameinfo.gameid)
							version  = string.split(version,"_") or {}
							version = trim(version[1] or "0")
							print("2222roomlist_layer>>>>>>", _severcfg_zipver , version)
							local _Active =  _severcfg_zipver ~= version
							local path = appdf.gamepath
							-- _Active = _Active or not cc.FileUtils:getInstance():isDirectoryExist(path)
			
							-- print("roomlist_layer>>>>>>",_Active,path,cc.FileUtils:getInstance():isDirectoryExist(path))
							gameinfo._Active = _Active
							downFlag:setVisible(_Active)
							if animat then
								if _Active == true then
									if self.mAniTable[gameinfo.gameid] ~= nil and self.mAniTable[gameinfo.gameid].format == "cocos" then
										animat:gotoAndPause(1)
									end
								else
									if self.mAniTable[gameinfo.gameid] ~= nil and self.mAniTable[gameinfo.gameid].format == "spine" then
										if gameinfo.gameid == yl.fruitslot then
											self.mAniTable[yl.fruitslot].node:setVisible(true)
										end
										animat:setAnimation(0, "animation", true)
									end
								end
							end
							
						end
					end
				end

                --如果房间状态为2，显示期待
                if gameinfo.status == 2 then
                    local Panel_wait = ccui.Layout:create()
                --    Panel_wait:setBackGroundColorOpacity(180)
                 --   Panel_wait:setBackGroundColorType(LAYOUT_COLOR_SOLID)
		            Panel_wait:setBackGroundColor(cc.c3b(0,0,0))
                    local waitSize = cc.size(bt:getContentSize().width-20,bt:getContentSize().height-10)
                    Panel_wait:setContentSize(waitSize)
                    Panel_wait:move(10,2)
                    Panel_wait:addTo(bt)
					Panel_wait:setName("Panel_wait")
					display.newSprite("GameList/downFlag.png"):move(bt:getContentSize().width/2-10.5,bt:getContentSize().height/2-1):addTo(Panel_wait)
                    display.newSprite("plaza/plazz/wait.png"):move(229,163):setName("wait"):addTo(Panel_wait)
                elseif gameinfo.status == 0 then
                    bt:setVisible(false)
				elseif gameinfo.status == 1 then
					bt:removeChildByName("Panel_wait")
                end
                
			else
				bt:setVisible(false)
			end	
				
		end	
		self.gameListView:pushBackCustomItem(itemlistView)	
	end
	 self.gameListView:setVisible(true)
	 self.gameListView:setItemsMargin(0)
end	
	local bvisible = self._scene:getTuiguanVisible( )
	if bvisible then
		self.share_page:setTouchEnabled(true) -- 隐藏推广按钮 by djy
		share_btn:addTouchEventListener(sharebtncallback)
		self:initPagePoint(2) -- 隐藏推广按钮 by djy
	else
		self.share_page:setTouchEnabled(false)
	end
	--[[self.share_page:addEventListener(function(sender,event)
        if event==ccui.PageViewEventType.turning then
			
			local pagenum = sender:getCurrentPageIndex()
			if pagenum >= 0 and pagenum < 2 then
				 self:selectPageBall(sender:getCurrentPageIndex()+1)
			end
          
        
        end
    
    end)--]]
	self.canChangeNextPage = true  --用于 如果玩家在滑动途中 就不要自动翻页
	local listener = cc.EventListenerTouchOneByOne:create()
	--区域外取消显示
	self.nowpageIdx = 1
	local  onEndTouch = function(pTouch,pEvent)
		
		local pagenum = self.share_page:getCurrentPageIndex()
		if self.nowpageIdx > pagenum then
			self:addPageItem(pagenum,true)
		elseif self.nowpageIdx < pagenum then
			self:addPageItem(pagenum,false)
		end

		self:selectPageBall()
		self.canChangeNextPage = true
	end
	local onTouchBegan = function(pTouch,pEvent)	
		self.canChangeNextPage = false
		local point = pTouch:getLocation()  
		local rect = self.share_page:getBoundingBox()  
		if cc.rectContainsPoint(rect,point) == true then

			return true
		else
			return false
		end
		
	end
	local listener1 = cc.EventListenerTouchOneByOne:create() 
	self.listener1 = listener1
	listener1:setSwallowTouches(true)
	listener1:registerScriptHandler(onEndTouch,cc.Handler.EVENT_TOUCH_ENDED )
	listener1:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
	self.eventDispatcher = self.share_page:getEventDispatcher() --事件派发器  
    
	self.eventDispatcher:addEventListenerWithSceneGraphPriority(listener1,self.share_page) --分发监听事  
	
	local pageact1 = cc.DelayTime:create(10)
	local pagefun = cc.CallFunc:create(function ()
		if self.canChangeNextPage then
			self:playNextPage()  -- 隐藏推广按钮 by djy
		end
		
	end)
	self.share_page:runAction(cc.RepeatForever:create(cc.Sequence:create(pageact1,pagefun)))
	self:initCyclePageview()
	self:initDonwLoadList()
	self:btnanimation(notAni)
	self:onlyshow100()

	local events = {yl.EVENT_JACKPORT_UPDATE,yl.EVENT_JACKPORT_BIGPRECE}
	self.customlistener = appdf.initListener(events,function(evt)
		print("initCustomEventListener>>>>",evt.name)
		local data = evt.data
		if evt.name == yl.EVENT_JACKPORT_UPDATE then
			local data = evt.data
			for k,v in pairs(data.gamels) do
				if v.gameid == yl.fruitslot then
					local isbigprice = self.mAniTable[yl.fruitslot].node.isbigprice
					local ischange = v.jackpot/1000 > 30000 and true or false
					if ischange and  self.mAniTable[yl.fruitslot] ~= nil and self.mAniTable[yl.fruitslot].node:isVisible() == true and not isbigprice then
						if self.mAniTable[yl.fruitslot].node.animaIdx == 2 then
							self.mAniTable[yl.fruitslot].ani:setAnimation(0, "animation", true)
							self.mAniTable[yl.fruitslot].node.animaIdx = 1
						end
						self.mAniTable[yl.fruitslot].node:updateDigital_pool(self:GetPreciseDecimal(v.jackpot/1000,2))
					end
				end
			end
	elseif evt.name == yl.EVENT_JACKPORT_BIGPRECE and  self.mAniTable[yl.fruitslot] ~= nil and self.mAniTable[yl.fruitslot].node:isVisible() then
		---	local data1 = cjson.encode(evt.data)--.msg
			local data = cjson.decode(evt.data.msg)--.msg
			self.mAniTable[yl.fruitslot].ani:setAnimation(0, "zhongjiang", true)
			self.mAniTable[yl.fruitslot].node:updateDigital()
			self.mAniTable[yl.fruitslot].node.isbigprice = true
			self.mAniTable[yl.fruitslot].node.animaIdx = 2
			performWithDelay(self,function ()
				self.mAniTable[yl.fruitslot].node.isbigprice = false
			end,30)
		end
	end,self)
	
end
function RoomListLayer:comperEnterWithRoomid(roomid)
	local limitCount =  self:checkSeverCloseTiyan(roomid) --进入多少次后关闭房间
	if limitCount ~= 0 then
		local hasEntercount = tonumber(self.enterRoomidInfo[tostring( roomid)] or 0) 
		
		if limitCount < hasEntercount then
			return false
		else
			return true
		end
	else
		return true
	end
end
function RoomListLayer:addPageItem(nowpageIdx,isleft,isScroll)
	local items = self.share_page:getItems()
	local count = #items
	insertpageIdx = insertpageIdx or 0
	if not isleft then
		local item = self.share_page:getItem(0)
		item:retain()
		self.share_page:removePageAtIndex(0)
		self.share_page:addPage(item)--addPage
	
		item:release()
	else
		local item = self.share_page:getItem(count-1)
		item:retain()
		self.share_page:removePageAtIndex(count-1)
		self.share_page:insertPage(item,0)--addPage
		
		item:release()
	end
	if isScroll then
		
		self.share_page:setCurrentPageIndex(0) 
		self.share_page:scrollToPage(1) 
	else
		self.share_page:setCurrentPageIndex(1) 
	end
	
	self.nowpageIdx = 1
	
end
function RoomListLayer:initCyclePageview()
	self.share_page:insertPage(self:clone_AngentLayer(),0)
	self.share_page:addPage(self:clone_copyLayer())
	self.share_page:setCurrentPageIndex(1)
end
function RoomListLayer:clone_copyLayer()

	local item = self.share_copy_layer:clone()
	item:setTag(1)
	self.share_copy_layer:setTag(1)
	local share_copy_btn = item:getChildByName("share_btn")
	
	local sharesize = self.share_copy_layer:getContentSize()
	--ExternalFun.addArmatureWithCustomNode("datingdonghua_fenxiangyingdajiang",item,nil,cc.p(sharesize.width/2,sharesize.height/2-37))
	item:setSwallowTouches(false)
	share_copy_btn:setSwallowTouches(false)
	return item
	
end
function RoomListLayer:clone_AngentLayer()
	local item = self.share_angent_layer:clone()
	item:setTag(2)
	self.share_angent_layer:setTag(2)
	local share_btn = item:getChildByName("share_btn")
	share_btn:setSwallowTouches(false)
	self:addShareAgent(share_btn)
	return item
	
end


function RoomListLayer:GetPreciseDecimal(nNum, n)
    if type(nNum) ~= "number" then
        return nNum;
	end
	local tempdata = math.abs(nNum)
    n = n or 0;
    n = math.floor(n)
    if n < 0 then
        n = 0;
    end
    local nDecimal = 10 ^ n
    local nTemp = math.floor(tempdata * nDecimal);
	local nRet = nTemp / nDecimal;
	if nNum >= 0 then
		return nRet;
	else
		return -nRet;
	end
end


function RoomListLayer:addShareAgent(share_btn)

	local scale = 0.98
	local size = share_btn:getContentSize()
	
	
	local quanmingdaili = sp.SkeletonAnimation:create("plaza/Aram/angent/quanmingdaili.json", "plaza/Aram/angent/quanmingdaili.atlas", 1)
	quanmingdaili:setPosition(size.width/2-5,-5) 
	quanmingdaili:addTo(share_btn)
	quanmingdaili:setAnimation(0, "animation", true)
	quanmingdaili:setScale(1,1.02)
	
	local chouma = sp.SkeletonAnimation:create("plaza/Aram/angent/chouma.json", "plaza/Aram/angent/chouma.atlas", 1)
	chouma:setPosition(size.width/2+5,size.height/2-55) 
	chouma:addTo(share_btn)
	chouma:setAnimation(0, "animation", true)
	--chouma:setScale(scale)
	
	local shangmianzt = sp.SkeletonAnimation:create("plaza/Aram/angent/shangmianzt.json", "plaza/Aram/angent/shangmianzt.atlas", 1)
	shangmianzt:setPosition(size.width/2-5,size.height/2+100) 
	shangmianzt:addTo(share_btn)
	shangmianzt:setAnimation(0, "animation", true)
	--shangmianzt:setScale(0.92)
	
	local xiamianzt = sp.SkeletonAnimation:create("plaza/Aram/angent/xiamianzt.json", "plaza/Aram/angent/xiamianzt.atlas", 1)
	xiamianzt:setPosition(size.width/2-5,size.height/2-194) 
	xiamianzt:addTo(share_btn)
	xiamianzt:setAnimation(0, "animation", true)
--	xiamianzt:setScale(scale)
end
function RoomListLayer:onlyshow100()
	--self.two_Panel   self.gameListView
	if GlobalUserItem.onlyShowLand then
		self._scene:addGame100Searchpath()
		
		self.gameListView:setVisible(false)
		self.gameInfo = GlobalUserItem.roomwithGameidlist[100]
		self._scene.gameInfo = self.gameInfo
		local dst
		local subgameSRCpath = appdf.gamecodepath.."100.src.views.RoomView"
		local subgameRESpath = appdf.gamepath.."100/src/views/RoomView.luac"
		local subgameRESpath2 = appdf.gamepath.."100/src/views/RoomView.lua"
		
		if cc.FileUtils:getInstance():isFileExist(subgameRESpath) then
			local roomView = appdf.req(subgameSRCpath)
			dst =roomView:create(self._scene,self.gameInfo)
		elseif cc.FileUtils:getInstance():isFileExist(subgameRESpath2) then
			local roomView = appdf.req(subgameSRCpath)
			dst =roomView:create(self._scene,self.gameInfo)
		else
			dst = Room:create(self._scene, param,self.gameInfo)
		end
		dst:setPositionY(53)
		--local landnode = display.newNode()
		dst:setName("landnode")
		if not self._scene._sceneLayer:getChildByName("landnode") then
			self._scene._sceneLayer:addChild(dst)
		end
		
		--self.two_Panel:addChild(landnode)
	else
		self.gameListView:setVisible(true)
		self._scene._sceneLayer:removeChildByName("landnode")
	end
end
function RoomListLayer:btnanimation(notAni)
	if notAni  then
		return
	end
	local nowlistpx,nowlistpy = self.gameListView:getPosition()
	for k,v in pairs(animationlist) do
	--	v:setOpacity(0)
		v:setAnchorPoint(0.5,0.5)
	--	v:setPositionX(v:getPositionX()-100)
		v:setScale(0.98)
		local act1_1 = cc.DelayTime:create(k*0.1)--0.1
	--	local act1 = cc.FadeIn:create(0.3)--0.4
		local act1 = cc.DelayTime:create(0.1)
		local act2 = cc.ScaleTo:create(0.1,1.02)
		local act3 = cc.ScaleTo:create(0.1,0.98)
		local act4 = cc.ScaleTo:create(0.05,1)
		v:runAction(cc.Sequence:create(act1_1,act1,act2,act3,act4))
	end
	
end


---- 初始化  游戏加载状态
function RoomListLayer:initDonwLoadList()
	dump(yl.updateList,"yl.updateList")

	local app = self._scene:getApp()
	--更新版本号
	for i,v in pairs(yl.updateList) do
		local sender = tbGameBt[i]--self.two_Panel:getChildByTag(self.kindIDIndexList[i])
		if sender then
						local spMask = sender:getChildByName("download_mask")
						self["m_spDownloadMask"..i] =  spMask
						if nil ~= spMask then
							self.m_szMaskSize = spMask:getContentSize()			
						end
						local spTipLab = spMask:getChildByName("downbg"):getChildByName("download_mask_tip")
						local spjiantou = spMask:getChildByName("downbg"):getChildByName("download_mask_jt")
						spTipLab:setVisible(true)
						spjiantou:setVisible(false)
						if v ~= 0 then
							local permsg = string.format("%.f%%", v.progressPercent or 0)
							spTipLab:setString(permsg)
						end
						self["m_labDownloadTip"..i] = spTipLab
						self["m_labDownloadjt"..i] = spjiantou
						spMask:getChildByName("downbg"):setVisible(true)
				
			if v == 0 then
				--更新版本号
				for k,v in pairs(self.game_ver_list) do
					if tostring(k) == tostring(i) then
						-- v._Active = true
						yl.updateList[i] = nil
						local verinfo = string.split(v,"_") or {}
						local _zipver = verinfo[1] or "0"   --最新版本
						app:getVersionMgr():setResVersion(_zipver, i)	
						print("updateResult>>>>",_zipver,i)
						local gamename = yl.GAME_NOTICE_TYPE[tonumber(i)]
						showToast(self._scene,gamename.." 下载完成",2)
						if spMask then
							spMask:setVisible(false)
						end
						break
					end
				end
			else
				v:setSetUpDateClient(self)
				
			end
		end
	end

end

--子视图点击

function RoomListLayer:btnTouched(gameinfo,sender)
	ExternalFun.playClickEffect( )
	if  not gameinfo then
		showToast(self:getParent():getParent(),"未找到游戏信息！",2)
		return
	end
	
	if gameinfo.watch ~= 1  and  gameinfo.enterlimit and GlobalUserItem.lUserScore < gameinfo.enterlimit then
		self.queryLayer=QueryExit:create("当前房间进入需要"..(gameinfo.enterlimit/appdf.bili)..yl.UNIT.."，您金币不足，是否立即充值？", function (bReTry)
			if bReTry == true then
				self:onChangeShowMode(yl.SCENE_SHOP)
			end
		end,true)
		:setCanTouchOutside(false)
		:addTo(self)
		return
	end
	
	--下载/更新资源 clientscene:getApp
	local app = self:getParent():getParent():getApp()
	local version = app:getVersionMgr():getResVersion(gameinfo.gameid)
	self.curversion = version or ""

	-- 兼容旧版本
	self.curversion  = string.split(self.curversion,"_") or {}
	self.curversion  = trim(self.curversion[1] or "")

	
	local path = appdf.gamepath..gameinfo.gameid
 	-- local active = not cc.FileUtils:getInstance():isDirectoryExist(path)
	self:getRootNode():addGameSearchpath(gameinfo.gameid)
	dump(gameinfo,"gameinfo")

	local verinfo = string.split(self.game_ver_list[tostring(gameinfo.gameid)] or "","_") or {}
	local _zipver = trim(verinfo[1] or "0")   --最新版本
	local _zipmd5 = verinfo[2] or ""    --增量版本
	local _zipmd5_orgin = verinfo[3] or ""   --基础包版本
	print("btnTouched>>>>>>>>",_zipver , self.curversion,active,path)
	-- by djy 去掉debug情况判断，走子游戏热更新
	-- if _zipver ~= self.curversion and not appdf.APPSTORE_VERSION  then --
	if _zipver ~= self.curversion and  not appdf.isDebug and not appdf.APPSTORE_VERSION  then --
		self:updateGame(gameinfo,sender)
	else
		GlobalUserItem.nCurGameKind = gameinfo.gameid
		self:enterGameinfo(gameinfo)
	end
end

function RoomListLayer:enterGameinfo( gameinfo )
	if self._scene.Is_ChannelForce == 1 and GlobalUserItem.is_extension == 0 then
		showToast(self,"您必须绑定您的推荐人才能进入游戏",1)
		return
	end
	local roomcount = 0   --- 判断房间开启个数
	local defaultroom    --默认可以进入房间数据
	for i=1,#gameinfo.roomls do
		local room = gameinfo.roomls[i]
		if room.status > 0 then
			roomcount = roomcount + 1
			if room.status == 1 then
				defaultroom = defaultroom or room
			end
		end
	end
	if   yl.GAME_TYPE_BAIREN[gameinfo.gameid] then --因为退出游戏也需要拉取 tablelist  
			self:showPopWait()
			self._scene._gameFrame:onSelectGame(gameinfo.gameid)
			self:getParent():getParent():onChangeShowMode(yl.SCENE_ROOM, self.m_bQuickStart,gameinfo )
			GlobalUserItem.bNoroomList = false
	elseif roomcount >= 2 then
			self:showPopWait()
			self._scene._gameFrame:onSelectGame(gameinfo.gameid)
			self:getParent():getParent():onChangeShowMode(yl.SCENE_ROOM, self.m_bQuickStart,gameinfo )		
			GlobalUserItem.bNoroomList = false
	elseif defaultroom then
			GlobalUserItem.nCurCGameId = defaultroom.roomid
			if defaultroom.status ~= 1 then
				showToast(self, "房间正在维护", 4)
				return
			end
			defaultroom.gameid = gameinfo.gameid
			local data = defaultroom
			data.watch = data.watch or 0
			local lUserScore = GlobalUserItem.lUserScore or 0
			if data.watch == 0 and data.enterlimit > lUserScore then
				showToast(self._scene,"金币不足"..data.enterlimit/appdf.bili.."，请充值后重试")
				return
			elseif data.watch == 1 and data.enterlimit and data.enterlimit > lUserScore then

			end
		
			self:onEnterGame(defaultroom)
			GlobalUserItem.bNoroomList = true
	else
		showToast(self, "房间正在维护", 4)
		GlobalUserItem.bNoroomList = true
	end
end

function RoomListLayer:onEnterGame( gamedata, isQuickStart)
	dump(gameinfo,"  >>>  gameinfo")
	self:updateEnterGameInfo(gamedata)
	self.m_bQuickStart = isQuickStart

	GlobalUserItem.nCurRoomIndex = gamedata.level or 1
	GlobalUserItem.nCurGameKind = gamedata.roomid
	self:getParent():getParent().retryTime = 0
	self:getParent():getParent():onStartGame()

end
--更新游戏进入记录
function RoomListLayer:updateEnterGameInfo(info)
	self:getRootNode():updateEnterGameInfo(info)
end
--获取父场景节点(ClientScene)
function RoomListLayer:getRootNode( )
	return self:getParent():getParent()
end
function RoomListLayer:updateGame(gameinfo,sender)
	local updateinfo = yl.updateList[gameinfo.gameid]
	if updateinfo then
		print("m_labDownloadTip is isVisible>>>>>")
		showToast(self,"正在下载中",1)
		return
	end

	if tolua.isnull(self) or not self.onGameZipUpdate  then
		print("updateGame  is nil >>>>>")
		return
	end

	-- dump(gameinfo,"gameinfo")
	self:onGameZipUpdate(gameinfo)
	if nil ~= sender then		
		local spMask = sender:getChildByName("download_mask")
		
		if not tolua.isnull(spMask) then

			local downbg = spMask:getChildByName("downbg")
			downbg:setVisible(true)

			self["m_spDownloadMask"..gameinfo.gameid] =  spMask
			spMask:setVisible(true)

			if nil ~= spMask then
				self.m_szMaskSize = spMask:getContentSize()			
			end
			local spTipLab = downbg:getChildByName("download_mask_tip")
			local spjiantou = downbg:getChildByName("download_mask_jt")
			spTipLab:setVisible(true)
			spjiantou:setVisible(false)
			self["m_labDownloadTip"..gameinfo.gameid] = spTipLab
			self["m_labDownloadjt"..gameinfo.gameid] = spjiantou
			if nil ~= spTipLab then
				spTipLab:setString("0%")
			end
		end
	
	end
end


--更新游戏
function RoomListLayer:onGameZipUpdate(gameinfo,ts)
	--失败重试
	if not gameinfo  then
		self:showGameUpdateWait()
		return 
	end

	local updateinfo = yl.updateList[gameinfo.gameid]
	if updateinfo  then
		print("m_labDownloadTip is isVisible>>>>>")
		return
	end

	ts = ts or ""
	if not gameinfo and not self["_downgameinfo"..gameinfo.gameid] then 
		showToast(self,"无效游戏信息！",1)
		return
	end

	--记录
	if gameinfo ~= nil then
		self["_downgameinfo"..gameinfo.gameid] = gameinfo
	end

	local verinfo = string.split(self.game_ver_list[tostring(gameinfo.gameid)] or "","_") or {}
	local _zipver = verinfo[1] or "0"   --最新版本
	local _zipmd5 = verinfo[2] or ""    --增量版本
	local _zipmd5_orgin = verinfo[3] or ""   --基础包版本
	--兼容旧版本

	local path = self.downlist[self.downidx] or self.downlist[1]
	if not path then
		showToast(self,"下载路径错误",1)
		return
	end
	local newfileurl = path.."/phone/game/".._zipver.."/"..gameinfo.gameid..".zip?ts="..ts
	if self.curversion == "" then
		_zipmd5 = _zipmd5_orgin
		newfileurl = path.."/phone/game/".._zipver.."/0_"..gameinfo.gameid..".zip?ts="..ts
	end
	print("newfileurl>>>",newfileurl,self.curversion)

	print("newfileurl>>>",newfileurl)

	local dst = device.writablePath .. "download/game/"

	print(debug.traceback("", 2))
	-- print(debug.debug())
	--创建更新
	
	local _update = Update:create(newfileurl,dst,gameinfo.gameid,_zipmd5,self)
	_update.version = _zipver
	_update:upDateClient(self)

	yl.updateList[gameinfo.gameid] =  _update


end

function RoomListLayer:onUpdataNotify()
	showToast(self,"游戏版本信息错误！",1)
end

function RoomListLayer:showGameUpdateWait()
	self.m_bGameUpdate = true
	-- ExternalFun.popupTouchFilter(1, false, "游戏更新中,请稍候！")
end

--更新进度
function RoomListLayer:updateProgress(sub, msg, mainpersent,kindID)
	local permsg = string.format("%.f%%", mainpersent)
	print("updateProgress>>>>>>",permsg,self["m_labDownloadTip"..kindID],kindID)
	if not tolua.isnull(self["m_spDownloadMask"..kindID]) then
		local scale = (101 - mainpersent) / 100		
		local downbg = self["m_spDownloadMask"..kindID]:getChildByName("downbg")
		if downbg then
			local propressTimer = downbg:getChildByName("download_mask_sp")
			if propressTimer then
				propressTimer:setPercentage(mainpersent)
			end
		end
	end

	if not tolua.isnull(self["m_labDownloadTip"..kindID]) then
		self["m_labDownloadTip"..kindID]:setString(permsg)
		self["m_labDownloadjt"..kindID]:setVisible(false)
		self["m_labDownloadTip"..kindID]:setVisible(true)
	else
		-- self:initDonwLoadList()
	end


end

--更新结果
function RoomListLayer:updateResult(result,msg,kindID)
	print("updateResult>>>>>>",result,msg,kindID)
	
	self:dismissGameUpdateWait()
	if result == true then
		showToast(self,msg or "下载成功",1)
		local app = self:getParent():getParent():getApp()
		if nil ~= self["m_spDownloadMask"..kindID] then
			self["m_spDownloadMask"..kindID]:setVisible(false)
			if self["m_spDownloadMask"..kindID].animat  then
				if self.mAniTable[kindID].format == "cocos" then
					self["m_spDownloadMask"..kindID].animat:play("Animation1")
				else
					self.mAniTable[kindID].ani:setAnimation(0, "animation", true)
					if yl.fruitslot == kindID then
						self.mAniTable[yl.fruitslot].node:setVisible(true)
					end
				end
			end
			if self["m_labDownloadTip"..kindID] then
				self["m_labDownloadTip"..kindID]:setVisible(false)
				self["m_labDownloadjt"..kindID]:setVisible(true)
				
			end
		end
		
		--更新版本号
		for k,v in pairs(self.game_ver_list) do
			if tostring(k) == tostring(kindID) then
				-- v._Active = true
				local verinfo = string.split(v,"_") or {}
				local _zipver = verinfo[1] or "0"   --最新版本
				app:getVersionMgr():setResVersion(_zipver, kindID)	
				print("updateResult>>>>",_zipver,kindID)
				local gamename = yl.GAME_NOTICE_TYPE[tonumber(kindID)]
				showToast(self._scene,gamename.." 下载完成",2)
				break
			end
		end
	else
		showToast(self,msg or "下载失败",2)
		local runScene = cc.Director:getInstance():getRunningScene()
		if nil ~= runScene then			

			if not tolua.isnull(self["m_labDownloadTip"..kindID]) then
				self["m_labDownloadTip"..kindID]:setString("")
				self["m_labDownloadjt"..kindID]:setVisible(true)
			end

			local spMask = self["m_spDownloadMask"..kindID]
			if  not tolua.isnull(spMask) then
				spMask:setVisible(true)
				local downbg = spMask:getChildByName("downbg")
				if not tolua.isnull(downbg) then
					downbg:setVisible(true)
					if downbg then
						local propressTimer = downbg:getChildByName("download_mask_sp")
						if propressTimer then
							propressTimer:setPercentage(0)
						end
					end
				end
			end

			--重试一次
			if not self["retryDown"..kindID] then
				self["retryDown"..kindID] =  true
				self.downidx = self.downidx + 1 
				if self.downidx > #self.downlist then
					self.downidx = 1
				end
				self:onGameZipUpdate(self["_downgameinfo"..kindID],os.time())
				return
			end
			if not tolua.isnull(self["dialog"..kindID] ) then
				self["dialog"..kindID]:removeSelf()
			end
			local  kindname = yl.GAME_NOTICE_TYPE[kindID] or ""
			if kindname ~= "" then
				kindname = " "..kindname.." "
			end
			self["dialog"..kindID] = QueryDialog:create(kindname..msg,function(bReTry)
					
					if bReTry == true and self["_downgameinfo"..kindID]  then
						self.downidx = self.downidx + 1 
						if self.downidx > #self.downlist then
							self.downidx = 1
						end
						self:onGameZipUpdate(self["_downgameinfo"..kindID],os.time())
						local downbg = spMask:getChildByName("downbg")
						if not tolua.isnull(downbg) then
							downbg:setVisible(true)
						end
					end
					self["dialog"..kindID]  = nil
				end)
				:addTo(runScene)
		end		 
		
	end
end

function RoomListLayer:dismissGameUpdateWait()
	self.m_bGameUpdate = false
	ExternalFun.dismissTouchFilter()
end

--显示等待
function RoomListLayer:showPopWait(gameid)
	if self._scene then
		self._scene:showPopWait(nil,gameid)
	end
end

--关闭等待
function RoomListLayer:dismissPopWait()
	if self._scene then
		self._scene:dismissPopWait()
	end
end


function RoomListLayer:onStartGame(index)
	local iteminfo = GlobalUserItem.GetRoomInfo(index)
	if iteminfo ~= nil then
		self._scene:onStartGame(index)
	end
end

--添加翻页小球
function RoomListLayer:initPagePoint(pointnum)
--	pointnum = 2
	local offsetX 
	if pointnum == 1 then
		offsetX = 20
	else
		offsetX = 30
	end
	self.tbballImg = {}
	local contentSize = cc.size(offsetX*pointnum,15)
	local listView = self.pagelayer:getChildByName("pageListView") 
	if not listView then
		listView = ccui.ListView:create()
		listView:setAnchorPoint(cc.p(0.5,0.5))
		listView:setName("pageListView")
		listView:setTouchEnabled(false)
		listView:setDirection(ccui.ScrollViewDir.horizontal)
		listView:setGravity(ccui.ListViewGravity.centerHorizontal)
		
		if pointnum == 1 then
			listView:setItemsMargin(0) 
		else
			listView:setItemsMargin(offsetX-16) 
		end
	--	ExternalFun.FixCenterUI(listView)
		listView:setPosition(cc.p(153,21))--140
		listView:setScrollBarEnabled(false)
		self.pagelayer:addChild(listView,1000)
	--	ExternalFun.FixCenterUI(listView)
--	ExternalFun.FixScaleUI(listView)
		
	else
		listView:removeAllItems()
		
	end
	listView:setContentSize(contentSize) 
	for i=1,pointnum do
		
		local img = ccui.ImageView:create("plaza/plazz/pointl.png")
		self.tbballImg[i] = img
		listView:pushBackCustomItem(img)
	end
	self:selectPageBall(1)
	--self.share_page:scrollToPage(0)
end
function RoomListLayer:selectPageBall(froceIdx)
	local pagenum = self.share_page:getCurrentPageIndex()
	pagenum = pagenum < 0 and 0 or pagenum
	local item = self.share_page:getItem(pagenum)
	local itemtag = froceIdx and froceIdx or item:getTag()
	if not self.tbballImg  then
		return
	end
	for k,v in pairs(self.tbballImg) do
		if itemtag == k then
			v:loadTexture("plaza/plazz/pointh.png")
		else
			v:loadTexture("plaza/plazz/pointl.png")
		end
	end
end
function RoomListLayer:playNextPage()
	local pagenum = self.share_page:getCurrentPageIndex()
	local item = self.share_page:getItem(pagenum)
	local itemtag = item:getTag()
	
	self:addPageItem(pagenum + 1,false,true)
	if itemtag == 1 then
		self:selectPageBall(2)
	else
		self:selectPageBall(1)
	end
	
end
return RoomListLayer